package com.qding.park.manager.service.core.facade.impl.common;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qding.park.common.core.exceptions.BaseException;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.business.manager.service.ServiceCoreException;
import com.qding.park.common.core.restborder.BorderStatuTran;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.manager.cache.UserCacheInter;
import com.qding.park.manager.common.pojo.ParkDataResult;
import com.qding.park.manager.facade.core.service.common.HisCommonFacade;
import com.qding.park.manager.pojo.TbCarlock;
import com.qding.park.manager.pojo.TbHistoryRecord;
import com.qding.park.manager.pojo.TbInvitecard;
import com.qding.park.manager.pojo.TbMonthRent;
import com.qding.park.manager.pojo.TbReserve;
import com.qding.park.manager.pojo.TbUserInfo;
import com.qding.park.manager.pojo.enums.CarLockStatusEnum;
import com.qding.park.manager.pojo.enums.OrderSourceEnum;
import com.qding.park.manager.pojo.enums.UserTypeEnum;
import com.qding.park.manager.pojo.example.HisExample;
import com.qding.park.manager.service.core.atomic.distributed.UserDBAtomic;
import com.qding.park.manager.service.core.biz.CarBiz;
import com.qding.park.manager.service.core.biz.HistoryBiz;
import com.qding.park.manager.service.core.biz.OutLineBiz;
import com.qding.park.manager.service.core.mapper.TbCarlockMapper;
import com.qding.park.manager.service.core.mapper.TbHistoryRecordMapper;
import com.qding.park.manager.service.core.mapper.TbInvitecardMapper;
import com.qding.park.manager.service.core.mapper.TbMonthRentMapper;
import com.qding.park.manager.service.core.mapper.TbParkspaceMapper;
import com.qding.park.manager.service.core.mapper.TbReserveMapper;
import com.qding.park.manager.service.core.mapper.TbUserInfoMapper;


@Service("hisCommonFacade")
public class HisCommonFacadeImpl implements HisCommonFacade {

    @Autowired
    private TbUserInfoMapper tbUserInfoMapper;

    @Autowired
    private TbParkspaceMapper tbParkspaceMapper;

    @Autowired
    private TbHistoryRecordMapper tbHistoryRecordMapper;
    
    /**
     * @Field @tbReserveMapper : TODO(预定、临停缴费)
     */
    @Autowired
    private TbReserveMapper tbReserveMapper;
    
    /**
     * @Field @tbMonthRentMapper : TODO(这里用一句话描述这个类的作用)
     */
    @Autowired
    private TbMonthRentMapper tbMonthRentMapper;
    
    @Autowired
    private TbInvitecardMapper  tbInvitecardMapper;
    
    @Autowired
    private  CarBiz  carBiz;
    
    @Autowired
    private  HistoryBiz  historyBiz;
    
    @Autowired
    private UserDBAtomic userDBAtomic;
    
    @Autowired
    private  OutLineBiz  outLineBiz;
    
    @Autowired
    private UserCacheInter  userCacheInter;
    
    @Autowired
    private TbCarlockMapper tbCarlockMapper;
    
    

    /*
     * (非 Javadoc) Description:
     * 
     * @see
     * com.qding.park.manager.facade.core.service.HistoryRecordFacade#recordList
     * (java.lang.String, int, int, int) 历史记录
     */
    @Override
    public ParkDataResult recordList(String bjuserid, int recordType, int jumpPage, int pageLength) {
        
        
        List<TbHistoryRecord> list=historyBiz.recordList(bjuserid,recordType,jumpPage,pageLength);
        PageInfo page = new PageInfo(list);
        List dataList = new ArrayList();
        for (TbHistoryRecord record : list) {
            Map<String, Object> map = new HashMap<String, Object>();
            if (record.getRecordType() == TbHistoryRecord.RecordTypeEnum.MONTHRENT_PAY.getCode()) {
                // 月租续费
                map.put("recordType", record.getRecordType());
                map.put("orderId", record.getOrderId());
                map.put("payFee", record.getPayFee());
                map.put("status", record.getStatus());
                map.put("orderSource", record.getOrderSource());
                if(record.getPayFeeTime()!=null){
                    map.put("payFeeTime", record.getPayFeeTime().getTime()/1000);
                }else{
                    map.put("payFeeTime", 0);
                }
                
                dataList.add(map);
            } else if (record.getRecordType() == TbHistoryRecord.RecordTypeEnum.RESERVE_PAY.getCode()) {
                // 预定
                map.put("recordType", record.getRecordType());
                map.put("orderId", record.getOrderId());
                map.put("reserveIncheckTime", record.getReserveIncheckTime().getTime()/1000);
                map.put("status", BorderStatuTran.reserveStatusTran(record.getStatus()));
                map.put("orderSource", record.getOrderSource());
                if(record.getRealIncheckTime()!=null){
                    map.put("realIncheckTime", record.getRealIncheckTime().getTime()/1000);
                }else{
                    map.put("realIncheckTime", 0);
                }
                
                dataList.add(map);
            }else if(record.getRecordType() == TbHistoryRecord.RecordTypeEnum.RESERVE_STOPING_PAY.getCode()){
                //停泊中
                
            }else if (record.getRecordType() == TbHistoryRecord.RecordTypeEnum.TEMP_PAY.getCode()) {
                // 临停缴费
                map.put("recordType", record.getRecordType());
                map.put("payFee", record.getPayFee());
                map.put("orderId", record.getOrderId());
                map.put("status", record.getStatus());
                map.put("orderSource", record.getOrderSource());
                
                //线上和线下的缴费时间　　显示的是不一样的
                if(OrderSourceEnum.OUTLINE.getType()==record.getOrderSource()){
                    //线下 用出场时间当缴费时间
                    if(record.getPayFeeTime()!=null){
                        map.put("payFeeTime", record.getRealOutcheckTime().getTime()/1000);
                    }else{
                        map.put("payFeeTime", 0);
                    }
                }else {
                    //线上  
                    if(record.getPayFeeTime()!=null){
                        map.put("payFeeTime", record.getPayFeeTime().getTime()/1000);
                    }else{
                        map.put("payFeeTime", 0);
                    }
                }
                
                dataList.add(map);
            }
        }
        
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list",dataList);
        data.put("currentPage", page.getPageNum());
        data.put("numPerPage", page.getPageSize());
        data.put("totalCount", page.getTotal());
        data.put("hast", page.isHasPreviousPage());
        data.put("next", page.isHasNextPage());
        
        ParkDataResult parkDataResult=ParkDataResult.createObjDate();
        parkDataResult.putMapOnObj(data);

        return parkDataResult;
    }

    @Override
    public ParkDataResult recordInfo(String orderId, int recordType) {
        // TODO Auto-generated method stub
        ParkDataResult parkDataResult=ParkDataResult.createObjDate();
        Map<String,Object> map=new HashMap<String,Object>();
        if (recordType== TbHistoryRecord.RecordTypeEnum.MONTHRENT_PAY.getCode()) {
            // 月租续费
            TbMonthRent tbMonthRent=tbMonthRentMapper.queryMonthRentById(orderId);
            map.put("orderId", tbMonthRent.getId());
            map.put("monthNum", tbMonthRent.getBuyMonths());
            map.put("parkName", tbMonthRent.getParkName());
            map.put("carNum", tbMonthRent.getCarNum());
            map.put("payFeeTime", tbMonthRent.getUpdate_date()==null?0:tbMonthRent.getUpdate_date().getTime()/1000);
            map.put("expirationTime",tbMonthRent.getExpiredate()==null?0:tbMonthRent.getExpiredate().getTime()/1000);
            map.put("payFee", tbMonthRent.getCost());
            map.put("parkId", tbMonthRent.getParkID());
            map.put("orderSource", tbMonthRent.getOrderSource());
            parkDataResult.putMapOnObj(map);
            
        } else if (recordType == TbHistoryRecord.RecordTypeEnum.RESERVE_PAY.getCode()) {
            // 预定
            TbReserve tbReserve=tbReserveMapper.queryReservesInfoById(orderId);
            map.put("orderId", tbReserve.getId());
            map.put("reserveIncheckTime", tbReserve.getStartTime()==null?0:tbReserve.getStartTime().getTime()/1000);
            map.put("parkName", tbReserve.getParkName());
            map.put("carNum", tbReserve.getCarNum());
            map.put("status", BorderStatuTran.reserveStatusTran(tbReserve.getStatus()));
            map.put("reserverContect", tbReserve.getReserverContect());
            map.put("parkId", tbReserve.getParkID());
            map.put("orderSource", tbReserve.getOrderSource());
            parkDataResult.putMapOnObj(map);
        } else if (recordType == TbHistoryRecord.RecordTypeEnum.TEMP_PAY.getCode()) {
            // 临停缴费
            TbReserve tbReserve=tbReserveMapper.queryReservesInfoById(orderId);
            map.put("orderId", tbReserve.getId());
            if(tbReserve.getStartTime()!=null){
                map.put("reserveIncheckTime", tbReserve.getStartTime().getTime()/1000);
            }else{
                map.put("reserveIncheckTime", 0);
            }
            
            map.put("parkName", tbReserve.getParkName());
            map.put("carNum", tbReserve.getCarNum());
            map.put("carNum", tbReserve.getCarNum());
            map.put("realIncheckTime", tbReserve.getCheckInTime()==null?0:tbReserve.getCheckInTime().getTime()/1000);
            map.put("realOutcheckTime", tbReserve.getCheckOutTime()==null?0:tbReserve.getCheckOutTime().getTime()/1000);
            map.put("reserveIncheckTime", tbReserve.getStartTime()==null?0:tbReserve.getStartTime().getTime()/1000);
            map.put("payFee", tbReserve.getDeposit());
            map.put("parkId", tbReserve.getParkID());
            map.put("orderSource", tbReserve.getOrderSource());
            parkDataResult.putMapOnObj(map);
        }
        return parkDataResult;
    }

    @Override
    public ParkDataResult inviteList(String bjuserId, int jumpPage, int pageLength) {
        
//      TbUserInfo tbUserInfo = tbUserInfoMapper.queryUserByBjUserId(bjuserId);
        TbUserInfo tbUserInfo = tbUserInfoMapper.queryUseByBjuseridType(bjuserId, UserTypeEnum.REGISTER_USER.getType());
        int userId = tbUserInfo.getId();
        PageHelper.startPage(jumpPage, pageLength);
        
        
        List<TbInvitecard>  tbInvitecards= tbInvitecardMapper.listByUserId(userId);
        
        PageInfo page = new PageInfo(tbInvitecards);

        List dataList = new ArrayList();
        for (TbInvitecard record : tbInvitecards) {
            Map<String, Object> map = new HashMap<String, Object>();
            
            map.put("orderId", record.getId());
            map.put("parkId", record.getParkID());
            map.put("parkName", record.getParkName());
            map.put("carNum", record.getCarNum());
            map.put("visitIncheckTime", record.getCheckInTime()==null?0:record.getCheckInTime().getTime()/1000);
            map.put("visitTime", record.getStartTime()==null?0:record.getStartTime().getTime()/1000);
            map.put("status", record.getStatus());
            map.put("visitPurpose", record.getVisitPurpose());
            map.put("visitAddress", record.getVisitAddress());
            map.put("createDate", record.getCreate_date()==null?0:record.getCreate_date().getTime()/1000);
            
            dataList.add(map);
        }
        
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list",dataList);
        data.put("currentPage", page.getPageNum());
        data.put("numPerPage", page.getPageSize());
        data.put("totalCount", page.getTotal());
        data.put("hast", page.isHasPreviousPage());
        data.put("next", page.isHasNextPage());
        
        ParkDataResult parkDataResult=ParkDataResult.createObjDate();
        parkDataResult.putMapOnObj(data);
        return parkDataResult;
    }

    @Override
    public ParkDataResult paymentRecordList_rest_wx(long phone, String bjuserId, int jumpPage, int pageLength) throws BaseException{
        
        
//      TbUserInfo tbUserInfo = tbUserInfoMapper.queryUserByBjUserId(bjuserId);
//      TbUserInfo tbUserInfo = tbUserInfoMapper.queryUseByBjuseridType(bjuserId, UserTypeEnum.WX_VISITOR_USER.getType());
        
//      TbUserInfo  tbUserInfo=carBiz.getUserWX(phone, bjuserId);
//      TbUserInfo  tbUserInfo=carBiz.structure_loginUser(String.valueOf(phone),bjuserId,UserTypeEnum.WX_VISITOR_USER.getType());
        TbUserInfo  u=new TbUserInfo();
        u.setTel(phone);
        u.setBjCode(bjuserId);
        u.setUserType(UserTypeEnum.WX_VISITOR_USER.getType());
        TbUserInfo  tbUserInfo=userDBAtomic.register_loginUser(u);
        if(tbUserInfo==null){
                throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getId(),null
                        ,ExceptionMessage.createExceptionMessage(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getDesc(), "没有找到此用户信息",
                                "phone" + phone+",bjuserId"+bjuserId));
        }
        int userId=tbUserInfo.getId();
        /*************/
        HisExample example=new HisExample();
        example.setUserId(userId);
        List<HisExample.OtherUser> otherExamples=tbUserInfoMapper.otherHisExample(userId);
        example.setOthers(otherExamples);
        /*************/
        PageHelper.startPage(jumpPage, pageLength);
//      List<TbReserve>  tbReserves= tbReserveMapper.listpay(userId,DateUtils.addMonths(new Date(), -1));
        List<TbReserve>  tbReserves= tbReserveMapper.listpayByExample(example,DateUtils.addMonths(new Date(), -3));
        PageInfo page = new PageInfo(tbReserves);
        
        
        List dataList = new ArrayList();
        for (TbReserve reserve : tbReserves) {
            Map<String, Object> map = new HashMap<String, Object>();
            
            map.put("recordId", reserve.getId());
            map.put("createOrderTime",  reserve.getCreate_date()==null?0:reserve.getCreate_date().getTime()/1000);
            map.put("payStatus", BorderStatuTran.teneratPaymentStatusTran(reserve.getStatus()));
            map.put("parkName", reserve.getParkName());
            map.put("carNum", reserve.getCarNum());
            map.put("payFee", reserve.getDeposit());
            map.put("orderSource", reserve.getOrderSource());
            dataList.add(map);
        }
        return ParkDataResult.createListDate(dataList, page);
    }

    @Override
    public ParkDataResult paymentRecordInfo_rest_wx(String orderId) throws BaseException{
        // TODO Auto-generated method stub
        
        TbReserve tbReserve=tbReserveMapper.queryReservesInfoById(orderId);
        
//      if(tbReserve==null||tbReserve.getReserverType()!=ReserverTypeEnum.GENERATION.getType()){
        if(tbReserve==null){
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getDesc(), "没有找到此订单",
                            " orderId=" + orderId ));
        }
        
//      if(tbReserve.getStatus()!=ReserverStatusEnum.TEMP_PAY_UNPAYED.getStatus()){
//          throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getId(), null,
//                  ExceptionMessage.createExceptionMessage(
//                          ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getDesc(), "不可以取消息的订单",
//                          " orderId=" + orderId ));
//      }
        
        ParkDataResult parkDataResult=ParkDataResult.createObjDate();
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("szOrderId", tbReserve.getId());
        map.put("createOrderTime", tbReserve.getCreate_date()==null?0:tbReserve.getCreate_date().getTime()/1000);
        map.put("payStatus",  BorderStatuTran.teneratPaymentStatusTran(tbReserve.getStatus()));
        map.put("parkName", tbReserve.getParkName());
        map.put("parkId", tbReserve.getParkID());
        map.put("carNum", tbReserve.getCarNum());
        map.put("orderSource", tbReserve.getOrderSource());
        map.put("incheckTime", tbReserve.getCheckInTime().getTime()/1000);
        map.put("outcheckTime", tbReserve.getCheckOutTime().getTime()/1000);
        map.put("payFee", tbReserve.getDeposit());
        parkDataResult.putMapOnObj(map);
        return parkDataResult;
    }

    /* (non-Javadoc)
     * @see com.qding.park.manager.facade.core.service.HistoryRecordFacade#outLineRecordList(int, int, int, int)
     * 分页查询线下历史记录
     */
    @Override
    public List<TbHistoryRecord> outLineRecordList(int userId, int recordType, int jumpPage, int pageLength) {
        
        List<TbHistoryRecord> resultList=new ArrayList<TbHistoryRecord>();
        if(recordType==-1){
            //所有 的历史记录
            
        }else if(recordType==0){
            //预定
        }else if(recordType==1){
            //月 租续费
        }else if(recordType==2){
            //临停缴费
            outLineBiz.tempRecordList(userId,jumpPage,pageLength);
        }
        return resultList;
    }

    @Override
    public ParkDataResult lockCarList(String bjuserId, int jumpPage, int pageLength) throws BaseException{
        
        String userIdStr=userCacheInter.bjuserId2userId(bjuserId);
        if(StringUtils.isBlank(userIdStr)){
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getDesc(), "此用户不存在",
                            " bjuserId=" + bjuserId ));
        }
        int userId=Integer.valueOf(userIdStr);
        PageHelper.startPage(jumpPage, pageLength);
        
        
        List<TbCarlock> tbCarlocks=tbCarlockMapper.listByUserid(userId);
        
        PageInfo page = new PageInfo(tbCarlocks);

        List dataList = new ArrayList();
        for (TbCarlock record : tbCarlocks) {
            Map<String, Object> map = new HashMap<String, Object>();
            
            map.put("orderId", record.getId());
            map.put("parkId", record.getParkID());
            map.put("parkName", record.getParkName());
            map.put("carNum", record.getCarNum());
            map.put("startTime", record.getStartTime()==null?0:record.getStartTime().getTime()/1000);
            map.put("endTime", record.getEndTime()==null?0:record.getEndTime().getTime()/1000);
            map.put("status", record.getStatus());
            map.put("createDate", record.getCreate_date()==null?0:record.getCreate_date().getTime()/1000);
            if(record.getStatus()==CarLockStatusEnum.CANCEL_STATUS.getStatus()||
                    record.getStatus()==CarLockStatusEnum.OVERTIME_STATUS.getStatus()){
                map.put("unlockDate", record.getUpdate_date()==null?0:record.getUpdate_date().getTime()/1000);
            }
            
            dataList.add(map);
        }
        
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list",dataList);
        data.put("currentPage", page.getPageNum());
        data.put("numPerPage", page.getPageSize());
        data.put("totalCount", page.getTotal());
        data.put("hast", page.isHasPreviousPage());
        data.put("next", page.isHasNextPage());
        
        ParkDataResult parkDataResult=ParkDataResult.createObjDate();
        parkDataResult.putMapOnObj(data);
        return parkDataResult;
    }

    @Override
    public ParkDataResult inviteDel(String orderId) throws BaseException {
        
        tbInvitecardMapper.delete(orderId);
        return ParkDataResult.createEmpty();
    }

    @Override
    public ParkDataResult lockCarDel(String orderId) throws BaseException {
        tbCarlockMapper.delete(orderId);
        return ParkDataResult.createEmpty();
    }

    @Override
    public ParkDataResult recordDel(String orderId, int recordType) throws BaseException {
        if (recordType== TbHistoryRecord.RecordTypeEnum.MONTHRENT_PAY.getCode()) {
            // 月租续费
            tbMonthRentMapper.recordDel(orderId);
        } else if (recordType == TbHistoryRecord.RecordTypeEnum.RESERVE_PAY.getCode()) {
            // 预定
            tbReserveMapper.reservDel(orderId);
        } else if (recordType == TbHistoryRecord.RecordTypeEnum.TEMP_PAY.getCode()) {
            // 临停缴费
            tbReserveMapper.tempDel(orderId);
        }
        return ParkDataResult.createEmpty();
    }

    @Override
    public ParkDataResult paymentRecordDel_rest_wx(String recordId) throws BaseException {
        tbReserveMapper.tempDel(recordId);
        return ParkDataResult.createEmpty();
    }

}
